#include "stm32f10x.h"                  // Device header
#include "stdio.h"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "Delay.h"

uint8_t Serial_RxFlag;
uint8_t Serial_RxData;//?????????
char Serial_RxPacket[100];//???????char??,????????,???????????extern???????????

void Serial_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	USART_InitTypeDef USART_InitStruct;
	NVIC_InitTypeDef NVIC_InitStructure;
	
	//???????
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//??PA9?PA10???
	
	//????????
	
		//PA9??
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;   //TX???USART????????,?????????
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; 
	GPIO_Init(GPIOA, &GPIO_InitStruct);
		//PA10??
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;   
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; 
	GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	//??????USART

	USART_InitStruct.USART_BaudRate = 9600;//?????
	USART_InitStruct.USART_HardwareFlowControl =USART_HardwareFlowControl_None;  //?????
	USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;//?????????TX,????????RX
	USART_InitStruct.USART_Parity = USART_Parity_No;//????
	USART_InitStruct.USART_StopBits = USART_StopBits_1;//1????
	USART_InitStruct.USART_WordLength = USART_WordLength_8b;
	USART_Init(USART1,&USART_InitStruct);
	
	//???????
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStructure);
	
	
	
	USART_Cmd(USART1,ENABLE);//??USART?? 
}



uint8_t Serial_GetRxFlag(void) //???????????????????
{
	if(Serial_RxFlag == 1)
	{
		Serial_RxFlag = 0;
		return 1;
	}
	return 0;
}


void Serial_SendByte(uint8_t Byte)
{
	USART_SendData(USART1,Byte);//???????byte?????TDR
	//??????,??TDR??????????????????????
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET);
	//TXE???????????,??????????,?????????
	
}

void Serial_SendString(char *String) // ?????????
{
	uint8_t i;
	for(i=0;String[i]!=0;i++)
	{
		Serial_SendByte(String[i]);
	}
	
}

//????
//????????

void USART1_IRQHandler(void)//????
{
	
	if(USART_GetFlagStatus(USART1,USART_IT_RXNE)==SET)//?????
	{
		Serial_RxData=USART_ReceiveData(USART1);//??PC?????
		Serial_RxFlag=1;//????1
		
		USART_ClearITPendingBit(USART1,USART_IT_RXNE);//?????????
	}
}
uint8_t Serial_GetRxData(void)//??????????????
{
	
	return Serial_RxData;
	
}


void Serial_Printf(char *format, ...)
{
	char String[100];				//??????
	va_list arg;					//???????????????arg
	va_start(arg, format);			//?format??,???????arg??
	vsprintf(String, format, arg);	//??vsprintf???????????????????
	va_end(arg);					//????arg
	Serial_SendString(String);		//????????(???)
}
